package com.crm.system.service.impl.systemManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.entity.systemManager.CallManager;
import com.crm.model.vo.systemManager.CallImportVO;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.service.systemManager.CallManagerDbService;
import com.crm.system.service.systemManager.CallImportService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author renshaorong
 * @Date 2021/4/22
 */
@Service
public class CallImportServiceImpl implements CallImportService {

    @Autowired
    private SysCompanyDbService sysCompanyDbService;

    @Autowired
    private CallManagerDbService callManagerDbService;

    @Autowired
    private UserAccountDbService userAccountDbService;

    @Override
    public JSONObject importCall(List<CallImportVO> list) {
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //重复的行数
        String repeatIdStr = "";
        //失败行数
        String importFailIdStr = "";

        //存放重复线索对象集合
        List<JSONObject> repeatObject = new ArrayList<>();

        //以下数据在遍历中用到，避免多次查找
        //公司名称及ID对应map
        Map<String,String> companyMap = this.companyIdAndName();
        //用户名及ID对应map
        Map<String,String> userAccountMap = this.accountIdAndName();
        //当前登陆用户
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //是否超管
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        for (int i=0;i<list.size();i++) {
            //普管不允许上传非本公司信息
            if(!rs && !userAccount.getCompanyId().equals(companyMap.get(list.get(i).getCompanyName()))){
                //导入失败
                if(StringUtils.isBlank(importFailIdStr)){
                    importFailIdStr = String.valueOf(i+1);
                }else {
                    importFailIdStr = importFailIdStr +  "," + String.valueOf(i+1);
                }
            }else{
                //添加
                //查询号码是否重复 重复判定条件为号码
                String telNum = list.get(i).getTelephoneNumber();
                List<CallManager> repeatLists = callManagerDbService.getCallManagerListByTelNum(telNum);
                if(repeatLists.size() == 0){//不重复
                    CallManager callManager = addCallModel(list.get(i),companyMap,userAccountMap,userAccount);
                    Boolean insertResult = callManagerDbService.insertSelective(callManager);
                    if(insertResult){
                        //导入成功
                        importNum = importNum + 1;
                    }else {
                        //导入失败
                        if(StringUtils.isBlank(importFailIdStr)){
                            importFailIdStr = String.valueOf(i+1);
                        }else {
                            importFailIdStr = importFailIdStr +  "," + String.valueOf(i+1);
                        }
                    }
                }else {
                    //重复
                    if(StringUtils.isBlank(repeatIdStr)){
                        repeatIdStr = String.valueOf(i+1);
                    }else {
                        repeatIdStr = repeatIdStr + "," + String.valueOf(i+1);
                    }
                }
            }

        }
        jsonObject.put("importCallNum",importNum);
        jsonObject.put("repeatIdStr",repeatIdStr);
        jsonObject.put("importFailIdStr",importFailIdStr);
        return jsonObject;
    }


    //拼凑model
    public CallManager addCallModel(CallImportVO callImportVO, Map<String, String> companyMap, Map<String, String> userAccountMap, UserAccount userAccount){
        CallManager callManager = new CallManager();

        callManager.setCallId(CommonUtils.getGUID());
        callManager.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        callManager.setCreatePeopleId(userAccount.getAccountId());
        callManager.setCreateTm(new Date());
        callManager.setTelephoneNumber(callImportVO.getTelephoneNumber());

        //号码类型 0、中继号 1、本地号 2、全国号
        if("中继号".equals(callImportVO.getTypeStr())){
            callManager.setType((short) 0);
        }else if("本地号".equals(callImportVO.getTypeStr())){
            callManager.setType((short) 1);
        }else if("全国号".equals(callImportVO.getTypeStr())){
            callManager.setType((short) 2);
        }

        //使用状态 0可用/1禁用/2停用
        if("可用".equals(callImportVO.getStatusStr())){
            callManager.setUseStatus((short) 0);
        }else if("禁用".equals(callImportVO.getStatusStr())){
            callManager.setUseStatus((short) 1);
        }else if("停用".equals(callImportVO.getStatusStr())){
            callManager.setUseStatus((short) 2);
        }

        //分公司ID
        callManager.setCompanyId(companyMap.get(callImportVO.getCompanyName()));

        //所有人ID
        callManager.setAccountId(userAccountMap.get(callImportVO.getUserName()));

        return callManager;
    }

    /**
     * 公司名称-ID对应map，用于表格中分公司名称转为ID
     * @return
     */
    public Map<String,String> companyIdAndName(){
        List<SysCompany> companyList = sysCompanyDbService.selectSysCompanyList();

        Map<String,String> nameToId = new HashMap<>();

        for(SysCompany sysCompany : companyList){
            nameToId.put(sysCompany.getCompanyName(),sysCompany.getCompanyId());
        }
        return nameToId;
    }

    /**
     * 公司名称-ID对应map，用于表格中分公司名称转为ID
     * @return
     */
    public Map<String,String> accountIdAndName(){
        List<UserAccount> userAccountList = userAccountDbService.getAllAccountList();

        Map<String,String> nameToId = new HashMap<>();

        for(UserAccount userAccount : userAccountList){
            nameToId.put(userAccount.getUserName(),userAccount.getAccountId());
        }
        return nameToId;
    }
}
